package com.seeyon.apps.kkSample.utils.jdbc;

import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.util.JDBCAgent;
import org.apache.commons.logging.Log;
import org.apache.logging.log4j.util.Strings;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: L
 * @Description:
 * @Date: 创建于10:18 2022-10-24
 **/
public class JDBCAgentUtil {

    private static final Log LOG = CtpLogFactory.getLog(JDBCAgentUtil.class);

    /**
     * cap4表单的单表数据查询
     *
     * @param formTableBean
     * @param param         key值为： 操作符|表单控件名称|查询变量别名
     *                      操作符：	为空表示等于
     *                      !表示不等于
     *                      >表示大于
     *                      <表示小于
     *                      like表示模糊查询
     *                      in 表示包含，param的value为list或者数组
     *                      notin 表示不包含，param的value为list或者数组
     *                      表单控件名称:	表单控件名称或者formmain表中的字段（如：id, state, finishedflag等）
     * @return
     * @throws BusinessException
     */
    public static List<Map> doCap4FormQuery(FormTableBean formTableBean, Map<String, Object> param) throws BusinessException {
        Map map = new HashMap();
        StringBuilder sb = new StringBuilder("select * from ");
        sb.append(formTableBean.getTableName());
        sb.append(" where 1=1 ");
        for (String key : param.keySet()) {
            String operate = key.split("\\|")[0];
            String display = key.split("\\|")[1];
            String alias = "";
            try {
                alias = key.split("\\|")[2];
            } catch (Exception e) {
            }
            FormFieldBean field = formTableBean.getFieldBeanByDisplay(display);
            if (field != null) {
                display = formTableBean.getFieldBeanByDisplay(display).getName();
            }
            if (param.get(key) == null) {
                if (Strings.isEmpty(operate) || "=".equals(operate)) {
                    sb.append(" and " + display + " IS NULL ");
                } else {
                    sb.append(" and " + display + " IS NOT NULL ");
                }
            } else {
                if (Strings.isEmpty(operate) || "=".equals(operate)) {
                    sb.append(" and " + display);
                    sb.append(" = :" + alias);
                } else if ("!".endsWith(operate)) {
                    sb.append(" and (" + display);
                    sb.append(" <> :" + alias + " or " + display + " is null) ");
                } else if ("in".equals(operate)) {
                    sb.append(" and " + display);
                    sb.append(" in (:" + alias + ")");
                } else if ("notin".equals(operate)) {
                    sb.append(" and " + display);
                    sb.append(" not in (:" + alias + ")");
                } else if ("like".equals(operate)) {
                    sb.append(" and " + display);
                    sb.append(" like '%:" + alias + "%'");
                } else {
                    sb.append(" and " + display);
                    sb.append(" " + operate + " :" + alias);
                }
                map.put(alias, param.get(key));
            }
        }
        return doQuery(sb.toString(), map);
    }

    public static List<Map> doQuery(String str, Map params) throws BusinessException {
        JDBCAgent agent = new JDBCAgent(true, false);
        try {
//            if (MapUtils.isEmpty(params)) {
            if (params.isEmpty()) {
                agent.execute(str);
            } else {
                agent.executeNamedSql(str, params);
            }
            return agent.resultSetToList();
        } catch (Exception e) {
            LOG.error("#客开日志：数据查询失败!", e);
            throw new BusinessException(e);
        } finally {
            if (agent != null) {
                agent.close();
            }
        }
    }
}
